#include "precompiled.h"
#include "graphwidget.h"
using namespace std;
using namespace weo::ui;
GraphWidget::GraphWidget(QWidget* parent /*= 0*/, Qt::WFlags flags /*= 0*/) : QWidget(parent, flags)
{
    setAttribute(Qt::WA_OpaquePaintEvent);;
}
void GraphWidget::addValue(float value)
{
    if(m_Values.empty())
    {
        m_Min = value;
        m_Max = value;
    }
    else
    {
        if(value < m_Min) m_Min = value;
        else if(value > m_Max) m_Max = value;
    }
    m_Values.push_back(value);
}
void GraphWidget::clear()
{
    m_Values.clear();
    m_Max = 0;
    m_Min = 0;
    update();
}
void GraphWidget::paintEvent ( QPaintEvent * event )
{     
    QPainter painter(this);
    unsigned int height = this->size().height();
    unsigned int width = this->size().width();
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(0,0,width,height,QBrush(Qt::white));
    QPen pen(Qt::black);
    pen.setWidth(2);
    painter.setPen(pen);
    painter.drawLine(10,10,10,height-10);
    painter.drawLine(10,height-9,width-10,height-9);
    float drawheight = height-10.0f;
    float drawwidth = width-10.0f;
    int startindex = max<int>(1, m_Values.size() - (int) drawwidth);
    if(m_Values.size() <= 1) return;
    QPoint start;
    QPoint stop;
    start.setX(10);
    start.setY((int) max<float>(drawheight-((drawheight-10)/(m_Max-m_Min))*(m_Values[0]-m_Min)+0.5f,10.0f));
    painter.drawText(drawwidth-40,drawheight-2,QString::number(m_Max));
    painter.drawText(15,20,QString::number(m_Values.size()));
    for(unsigned int k = startindex;k<m_Values.size();k++)
    {
        stop.setX((int) max<float>((k*drawwidth/(m_Values.size()-1))+10.5f,10.0f));
        stop.setY((int) max<float>(drawheight-((drawheight-10)/(m_Max-m_Min))*(m_Values[k]-m_Min)+0.5f,10.0f));
        painter.drawLine(start,stop);
        start = stop;
    }
}